/*
 * Copyright (C) 2012 Johan Boris Iantila jiantila@gmail.com && http://www.facebook.com/johanboris.iantila
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package mg.daloji.antandroyd.ui;



import mg.daloji.antandroyd.CONSTANTS;
import mg.daloji.antandroyd.R;
import mg.daloji.antandroyd.Radio;
import mg.daloji.antandroyd.application.App;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;



/**
 *
 * @author Johan Boris Iantila
 *
 */

public class Main extends SherlockActivity implements ActionBar.OnNavigationListener {
	
	private ProgressDialog mWaitDialog;
	private int radioselected;
	private ListView mlist;
	private LazyAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setTheme(R.style.Theme_Sherlock);
	
		Context context = getSupportActionBar().getThemedContext();
		//ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.locations, R.layout.sherlock_spinner_item);
		//list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_CUSTOM);
		getSupportActionBar().setHomeButtonEnabled(true);
		//getSupportActionBar().setListNavigationCallbacks(list, this);
	        
		if(haveNetworkConnection()){
			mlist=(ListView)findViewById(R.id.list);
			adapter=new LazyAdapter(this,App.getConf());        
			mlist.setAdapter(adapter);
			mlist.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {	
					radioselected=position;
					Intent intent =new Intent(getApplicationContext(),Home.class);
					intent.putExtra(CONSTANTS.INDEX,radioselected);
					startActivity(intent);
				}
			});
		}else{
			showError();
		}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getSupportMenuInflater().inflate(R.menu.main,  menu);
		return false;
	}
	  
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		
		//Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG).show();
		return super.onTouchEvent(event);
	}
	  
	  /**
		 * Dismisses the wait dialog if any
		 */
		void hideWaitDialog() {
			if (null != this.mWaitDialog) {
				this.mWaitDialog.dismiss();
			}
		}
	  /**
	   * 
	   * @author daloji
	   *
	   */
	  public class Receiver extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				hideWaitDialog();
			}
			
		}
	  

	  public final boolean isInternetOn()
	  {
		  boolean state=false;
		  ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		  if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
				  connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ){
			  state= true;
		  }
		  else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
				  ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  )
		  {
			  state=false;
		  }
		  return state;
	  }
	  
	  
	  private boolean haveNetworkConnection() {
		    boolean haveConnectedWifi = false;
		    boolean haveConnectedMobile = false;

		    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		    for (NetworkInfo ni : netInfo) {
		        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
		            if (ni.isConnected())
		                haveConnectedWifi = true;
		        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
		            if (ni.isConnected())
		                haveConnectedMobile = true;
		    }
		    return haveConnectedWifi || haveConnectedMobile;
		}
	
	  
	  void showError() {
	        final AlertDialog.Builder builder =  new AlertDialog.Builder(this)
	            .setTitle(R.string.app_name) 
	            .setMessage(R.string.service_error_network)
	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setCancelable(false);
	        
	        builder.setPositiveButton(R.string.service_positive_error_network,new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	               finish();
	          } }); 
	        builder.show();
	        
	  }
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
	  //  mSelected.setText("Selected: " + mLocations[itemPosition]);
		Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG).show();
        return true;
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	  
	
}